package com.mical.demo.service;

import com.mical.demo.dto.LoginRequest;
import com.mical.demo.dto.LoginResponse;
import com.mical.demo.model.User;
import com.mical.demo.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    private final UserService userService;

    @Autowired
    public AuthService(AuthenticationManager authenticationManager,
                       JwtTokenUtil jwtTokenUtil,
                       UserService userService) {
        this.authenticationManager = authenticationManager;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    public LoginResponse authenticateUser(LoginRequest loginRequest) throws AuthenticationException {
        // 清除之前可能存在的认证
        SecurityContextHolder.clearContext();

        // 使用Spring Security认证用户
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );

        // 设置新的认证
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成新的JWT token
        String jwt = jwtTokenUtil.generateToken(authentication);

        // 从数据库获取用户详细信息
        User user = userService.loadUserByUsername(loginRequest.getUsername());

        // 创建并返回登录响应
        return new LoginResponse(
                jwt,
                user.getId(),
                user.getUsername(),
                user.getRole()
        );
    }

    public void logout(String token) {
        // 使当前token失效
        jwtTokenUtil.invalidateToken(token);

        // 清除安全上下文
        SecurityContextHolder.clearContext();
    }
}